<template>
  <div class="hospital-nav">
    <div class="map-container">
      <div id="map" ref="map"></div>
    </div>
    <div class="search-container">
      <el-input
          placeholder="输入医院名称或地址"
          v-model="searchKeyword"
          @keyup.enter="searchHospitals"
          class="search-input"
      >
        <template #append>
          <el-button @click="searchHospitals">搜索</el-button>
        </template>
      </el-input>
    </div>
    <div v-if="routeInfo" class="route-info-box">
      <h4>路线信息</h4>
      <p>距离：{{ routeInfo.distance }}</p>
      <p>预计时间：{{ routeInfo.duration }}</p>
      <p>起点：{{ routeInfo.start }}</p>
      <p>终点：{{ routeInfo.end }}</p>
      <el-button size="small" @click="clearRoute" style="float:right;">清除路线</el-button>
    </div>
    <div class="hospital-list">
      <h3>附近儿童医院</h3>
      <div class="hospital-item" v-for="(hospital, index) in hospitals" :key="index">
        <h4>{{ hospital.name }}</h4>
        <p>{{ hospital.address }}</p>
        <div class="actions">
          <el-button type="primary" size="small" @click="navigateToHospital(hospital)">导航</el-button>
        </div>
      </div>
      <div v-if="hospitals.length === 0">
        <p>未找到附近的医院，请尝试其他关键词或位置。</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 高德地图的 API Key 和安全密钥
const gaodeKey = '1618cb3ea5acb4630432377d4c0dfaac'
const securityJsCode = 'e337b9acb193f7a78144a64cbd1a3506'

// 页面元素引用
const map = ref(null)

// 搜索结果关键词绑定的关键词
const searchKeyword = ref('医院')

// 存储搜索到的医院结果
const hospitals = ref([])

// 存储用户当前位置
const currentPosition = ref(null)

// 存储当前路线对象，便于清除
const currentRoute = ref(null)

// 路线信息展示
const routeInfo = ref(null);

// 初始化地图
let amap = null

// 城市名称转换为中文
const translateCityName = (city, region) => {
  const cityMap = {
    'Beijing': '北京',
    'Shanghai': '上海',
    'Guangzhou': '广州',
    'Shenzhen': '深圳',
    'Zhengzhou': '郑州',
    'Hangzhou': '杭州',
    'Nanjing': '南京',
    'Wuhan': '武汉',
    'Chengdu': '成都',
    'Xi\'an': '西安',
    'Chongqing': '重庆',
    'Tianjin': '天津'
  }

  const regionMap = {
    'Beijing': '北京',
    'Shanghai': '上海',
    'Guangdong': '广东',
    'Henan': '河南',
    'Zhejiang': '浙江',
    'Jiangsu': '江苏',
    'Hubei': '湖北',
    'Sichuan': '四川',
    'Shaanxi': '陕西',
    'Chongqing': '重庆',
    'Tianjin': '天津'
  }

  const chineseRegion = regionMap[region] || region
  const chineseCity = cityMap[city] || city

  return `${chineseRegion}${chineseCity}`
}

onMounted(() => {
  initMap()
})



// 初始化地图
const initMap = () => {
  if (window.AMap) {
    createMap()
  } else {
    loadGaodeMapAPI()
  }
}

// 动态加载高德地图 API
const loadGaodeMapAPI = () => {
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = `https://webapi.amap.com/maps?v=2.0&key=${gaodeKey}&callback=createMap`
  document.head.appendChild(script)

  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  }
}

// 创建地图实例
const createMap = () => {
  if (window.AMap) {
    amap = new window.AMap.Map(map.value, {
      center: [116.397428, 39.90923], // 默认北京中心点
      zoom: 12
    })
    searchNearbyHospitals()
  } else {
    ElMessage.error('地图加载失败，请刷新页面重试')
  }
}

// 搜索包含的搜索医院功能
const searchHospitals = () => {
  if (!amap) {
    ElMessage.error('地图尚未加载完成，请稍后再试')
    return
  }
  performPlaceSearch(searchKeyword.value, null, true)
}

// 搜索功能 - 使用第三方IP定位
const searchNearbyHospitals = () => {
  if (!amap) return

  // 使用第三方IP定位服务
  getThirdPartyIpLocation()
}



// 使用第三方IP定位服务
const getThirdPartyIpLocation = async () => {
  try {
    // 使用 ipapi.co 服务
    const response = await fetch('https://ipapi.co/json/')
    const data = await response.json()

    if (data.latitude && data.longitude) {
      // 保存用户当前位置
      currentPosition.value = [data.longitude, data.latitude]

      // 更新地图中心点
      amap.setCenter(currentPosition.value)

      // 搜索附近医院
      performPlaceSearch('医院', currentPosition.value)

      // 显示中文城市名称
      const chineseCityName = translateCityName(data.city, data.region)
      ElMessage.success(`定位成功 - ${chineseCityName}`)
    } else {
      useDefaultLocation()
    }

  } catch (error) {
    ElMessage.error('定位失败，使用默认位置')
    useDefaultLocation()
  }
}

// 使用默认位置
const useDefaultLocation = () => {
  const defaultPosition = [116.397428, 39.90923]
  currentPosition.value = defaultPosition
  amap.setCenter(currentPosition.value)
  performPlaceSearch('医院', currentPosition.value)
  ElMessage.warning('使用默认位置（北京）')
}



// 执行地点搜索
const performPlaceSearch = (keyword, position = null, autoNavigate = false) => {
  // 确保先加载 PlaceSearch 插件
  window.AMap.plugin('AMap.PlaceSearch', () => {
    const placeSearch = new window.AMap.PlaceSearch({
      pageSize: 9999,
      extensions: 'all',
      types: '医院',
      city: '全国' // 搜索框限在全国范围搜索
    })

    const callback = (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          hospitals.value = result.poiList.pois
          addMarkersToMap(result.poiList.pois)
          // 如果是输入目的地且只有一个结果，自动导航
          if (autoNavigate && result.poiList.pois.length === 1) {
            navigateToHospital(result.poiList.pois[0])
          }
        } else {
          ElMessage.warning('未找到附近的医院，请尝试其他关键词或位置')
          hospitals.value = []
        }
      } else {
        ElMessage.error('搜索失败，请稍后再试')
      }
    }

    // 如果有指定位置，则使用该位置作为搜索中心点
    if (position) {
      placeSearch.searchNearBy(keyword, position, 10000, callback) // 增大搜索半径至10000米
    } else {
      // 如果没有指定位置，则使用用户当前位置（如果已知）
      if (currentPosition.value) {
        placeSearch.searchNearBy(keyword, currentPosition.value, 10000, callback)
      } else {
        placeSearch.search(keyword, callback)
      }
    }
  })
}

// 在地图上添加标记
const addMarkersToMap = (pois) => {
  if (!amap) return

  amap.clearMap() // 清除地图上的所有内容

  pois.forEach((poi) => {
    const marker = new window.AMap.Marker({
      position: [poi.location.lng, poi.location.lat]
    })
    amap.add(marker)
  })

  amap.setFitView()
}

// 导航到医院
const navigateToHospital = (hospital) => {
  if (!amap) return;
  if (!currentPosition.value) {
    ElMessage.error('请先允许定位，获取当前位置后再导航');
    return;
  }
  window.AMap.plugin('AMap.Driving', () => {
    const driving = new window.AMap.Driving({
      policy: window.AMap.DrivingPolicy.LEAST_DISTANCE,
      map: amap
    });
    const start = new window.AMap.LngLat(currentPosition.value[0], currentPosition.value[1]);
    const end = new window.AMap.LngLat(hospital.location.lng, hospital.location.lat);
    // 清除上一次路线
    if (currentRoute.value) {
      currentRoute.value.clear();
    }
    driving.search(start, end, (status, result) => {
      if (status === 'complete' && result.routes && result.routes.length > 0) {
        ElMessage.success('已为您规划路线');
        currentRoute.value = driving;
        // 解析路线信息
        const route = result.routes[0];
        routeInfo.value = {
          distance: (route.distance / 1000).toFixed(1) + '公里',
          duration: Math.round(route.time / 60) + '分钟',
          start: '当前位置',
          end: hospital.name
        };
      } else {
        ElMessage.error('导航失败，请稍后再试');
      }
    });
  });
};

// 清除路线
const clearRoute = () => {
  if (currentRoute.value) {
    currentRoute.value.clear();
    currentRoute.value = null;
  }
  routeInfo.value = null;
};
</script>

<style scoped>
.hospital-nav {
  padding: 20px;
}

.map-container {
  height: 500px;
  width: 100%;
  margin-bottom: 20px;
}

#map {
  height: 100%;
  width: 100%;
  border-radius: 8px;
}

.search-container {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  max-width: 500px;
}

.hospital-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.hospital-list h3 {
  margin-top: 0;
  color: #333;
}

.hospital-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.hospital-item:last-child {
  border-bottom: none;
}

.hospital-item h4 {
  margin: 0 0 5px;
  color: #409eff;
}

.hospital-item p {
  margin: 0 0 10px;
  color: #666;
}

.actions {
  text-align: right;
}

.route-info-box {
  background: #f0f8ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  padding: 18px 20px 30px 20px;
  margin-bottom: 20px;
  position: relative;
}
.route-info-box h4 {
  margin: 0 0 10px 0;
  color: #409eff;
}
.route-info-box .el-button {
  position: absolute;
  right: 20px;
  bottom: 10px;
}
</style>